package com.wlb365.admin.modules.devops.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlb365.admin.modules.devops.dto.IsvRoleDTO;
import com.wlb365.admin.modules.devops.entity.Keys;
import com.wlb365.admin.modules.devops.mapper.IsvRoleMapper;
import com.wlb365.admin.modules.devops.mapper.KeysMapper;
import com.wlb365.admin.modules.devops.service.KeysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * ISV秘钥
 * </p>
 *
 * @author
 * @since 2020-04-08 14:05:08
 */
@Service
public class KeysServiceImpl extends ServiceImpl<KeysMapper, Keys> implements KeysService {

    @Autowired
    private IsvRoleMapper isvRoleMapper;

    @Override
    public Page<Keys> listKeysPage(Keys keys) {
        Page<Keys> page = new Page<>(keys.getCurrent(), keys.getSize());
        List<OrderItem> orderItems = new ArrayList<>();
        orderItems.add(new OrderItem("id",false));
        page.setOrders(orderItems);
        List<Keys> keyss = baseMapper.selectKeysList(keys, page);
        return page.setRecords(keyss);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Keys keys, List<String> roleCodes) {
        baseMapper.updateById(keys);

        isvRoleMapper.deleteIsvRoleGroupByIsvId(keys.getId());

        this.saveRole(keys.getId(), roleCodes);
    }

    private void saveRole(Long isvId, List<String> roleCodes) {
        List<IsvRoleDTO> tobeSaveList = roleCodes.stream()
                .map(roleCode -> {
                    IsvRoleDTO rec = new IsvRoleDTO();
                    rec.setIsvId(isvId);
                    rec.setRoleCode(roleCode);
                    return rec;
                })
                .collect(Collectors.toList());
        if (tobeSaveList != null && tobeSaveList.size() > 0) {
            isvRoleMapper.insertIsvRoleBatch(tobeSaveList);
        }
    }
}
